package com.fuxi.cloud.common.expetion;

import com.fuxi.cloud.common.constant.ErrorCode;
import com.fuxi.cloud.common.vo.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * JimuGlobalExceptionHandler
 *
 * @Author: 扫地僧
 * @CreateTime: 2021-04-19
 */
@RestControllerAdvice
public class JimuGlobalExceptionHandler {
    private static final Logger log = LoggerFactory.getLogger(JimuGlobalExceptionHandler.class);

    public JimuGlobalExceptionHandler() {
    }

    @ExceptionHandler({JimuAlertException.class})
    public static Result openException(Exception ex, HttpServletRequest request, HttpServletResponse response) {
        response.setContentType("application/json; charset=utf-8");
        Result var3 = resolveException(ex, request.getRequestURI());
        response.setStatus(var3.getCode());
        return var3;
    }

    public static Result resolveException(Exception ex, String path) {
        ErrorCode var2 = ErrorCode.ERROR;
        int var3 = HttpStatus.INTERNAL_SERVER_ERROR.value();
        String var4 = ex.getMessage();
        String var5 = ex.getClass().getSuperclass().getName();
        String var6 = ex.getClass().getName();
        if (var6.contains("JimuAlertException")) {
            var3 = HttpStatus.OK.value();
            var2 = ErrorCode.ALERT;
        }

        return buildBody(ex, var2, path, var3);
    }

    private static Result buildBody(Exception exception, ErrorCode resultCode, String path, int httpStatus) {
        String var4 = exception.getMessage();
        if (resultCode == null) {
            resultCode = ErrorCode.ERROR;
        }

        int var5 = resultCode.getCode();
        Result var6 = Result.error(var5, var4);
        log.error("==> 错误:{} exception: {}", var6, exception);
        return var6;
    }
}

